package com.wv.api.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wv.api.mapper.SysUserDao;
import com.wv.api.service.ILoginService;
import com.wv.common.exception.WVException;
import com.wv.common.result.HttpCodeEnum;
import com.wv.model.system.SysUser;
import com.wv.utils.MD5EncryptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public SaResult login(String name, String password) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,name);
        // 查询是否有用户
        SysUser sysUser = sysUserDao.selectOne(wrapper);
        if (sysUser == null){
            throw new WVException(HttpCodeEnum.USER_EXISTENCE);
        }
        String s = MD5EncryptionUtil.EncodeByMd5(password, sysUser.getSalt());
        if (sysUser.getPassword().equals(s)){
            // 登录成功
            StpUtil.login(sysUser.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return SaResult.ok().setData(tokenInfo);
        }
        return SaResult.error("密码错误");
    }
}
